# Paper: Is it still the economy? Economic voting in polarized politics
# Individual-level simulation
# Replication: Figure S15 (Supplementary Material)
remove(list = ls())

library(conflicted)
library(tidyverse)
library(dplyr)
conflict_prefer("filter","dplyr")
library(ggplot2)
library(here) # When we have an R-project, it reads files without setting an directory
conflict_prefer("here", "here")
library(nnet)
library(ggeffects)
library(MASS)
conflict_prefer("select","dplyr")


load(here("Final_Paper", "R&R", "CountyLevel.RData"))
glimpse(model_data)

state_data <- model_data %>% 
  group_by(state_fips, year) %>% 
  summarise(unemp_state = mean(unemp_rate, na.rm = T)) %>% 
  ungroup() %>% 
  mutate(state_fips = as.factor(state_fips))
glimpse(state_data)

load(here("Final_Paper", "R&R", "IndLevel.RData"))
glimpse(model_data)


new_data <- left_join(model_data, state_data, by = c("state_fips", "year"))
glimpse(new_data)
sum(is.na(new_data$unemp_state))
missing_data <- new_data %>% filter(is.na(unemp_state))
table(missing_data$state_fips, missing_data$year)
remove(missing_data)

new_data <- new_data %>% filter(!is.na(unemp_state))

glimpse(new_data)
new_data <- new_data %>% 
  mutate(econ_eval2 = as.numeric(econ_eval))

summary(ml_inc <- lm(econ_eval2 ~ unemp_state + percep_polar*partisan + 
                       female + black + hispanic + asian + other_race + 
                       log_age + college + income, 
                     data = new_data))


summary(new_data$unemp_state)
model_pol <- ggeffect(ml_inc, terms = "unemp_state[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]", 
                      ci.lvl = 0.95)
glimpse(model_pol)
model_pol <- data.frame(model_pol)

f2 <- ggplot(model_pol, aes(x = x, y = predicted)) +
  geom_line(aes(), size = .75, color = "darkslategray") + 
  theme_light() +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = .1, 
              fill = "#008080") +
  ggtitle(NULL) +
  ylab("Economic Evaluation") +
  xlab("Mean Unemployment Rate (State)") +
  #ggtitle("(b) Relationship between Observed and Perceived Polarization") +
  #labs(linetype = "Party Id.") +
  scale_y_continuous(breaks = c(2, 1.8, 1.6)) +
  scale_x_continuous(breaks = c(2, 4, 6, 8, 10, 12, 14)) +
  theme(legend.position="bottom",
        axis.title = element_text(size = 13),
        axis.text = element_text(size = 11),
        legend.title = element_text(size = 13),
        title = element_text(size = 10),
        legend.text = element_text(size = 12))
f2


